import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { MemberService } from 'src/app/services/member.service';
import { MemberVo } from 'src/app/model/member-vo';
import { MemberStorageService } from 'src/app/services/member-storage.service';
import { BtnNaviSharedService } from 'src/app/services/btn-navi-shared.service';
import { HttpErrorResponse } from '@angular/common/http';
import { UtilService } from 'src/app/services/util.service';
import { Title } from '@angular/platform-browser';
import { FootmarkTrackService, ProcessURLResult } from 'src/app/services/footmark-track.service';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styles: [``]
})
export class LoginComponent implements OnInit {
  public member: { names: string, pswd: string, tries: number, redirect: string, trace: string, token: string, ip: string } = {
    names: '',
    pswd: '',
    tries: 0,
    redirect: '',
    trace: 'msa',
    token: '',
    ip: '127.0.0.1'
  };
  //登录成功的会员
  public activeMember!: MemberVo;
  public errorMessage: string = '';
  private previousUrl!: string | null;

  constructor(
    private title: Title,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private memberService: MemberService,
    private memberStorage: MemberStorageService,
    private util: UtilService,
    private footMark: FootmarkTrackService,
    private btnNaviSharedService: BtnNaviSharedService) {
    this.btnNaviSharedService.active(false); //不显示全局的导航
    this.member.token = this.util.randomAlphaNumeric(8) || '123456';
    this.memberStorage.getIpCliente().subscribe(ipAddr => this.member.ip = ipAddr);

  }

  ngOnInit(): void {
    //在线的情况下登录无意义
    if(this.memberStorage.get() !== null){
      this.router.navigate(['/home']);
    }
    this.title.setTitle('小伙伴正在等您开车呢');
    this.activatedRoute.queryParams.subscribe(params => {
      this.member.redirect = params['redirect'];
    });
    this.previousUrl = this.footMark.getReferer();
  }

  public checkIn(submitBtn: HTMLButtonElement): void {
    submitBtn.disabled = true;
    submitBtn.setAttribute('value', '正在提交数据...');
    //
    this.memberService.signIn(this.member.names, this.member.pswd, this.member.token, this.member.ip).subscribe({
      next: response => {
        this.activeMember = response;
      },
      error: err => {
        if (err instanceof HttpErrorResponse) {
          if (err.error instanceof ErrorEvent) {
            this.errorMessage = err.error.message;
          } else {
            this.errorMessage = (err.status === 404) ? '用户名或密码不匹配' : err.error;
          }
        } else if (err instanceof Error) {
          this.errorMessage = err.message;
        } else { this.errorMessage = err; }
        this.member.tries += 1;
        //
        submitBtn.disabled = false;
        submitBtn.setAttribute('value', '马上登陆');
      },
      complete: () => {
        console.log('[MemberLogin-CTL]Completed');
        this.storeMember();
      }
    });
  }

  private storeMember(): void {
    if (this.activeMember && this.activeMember.id > 0) {
      //压入缓存
      this.memberStorage.set(this.activeMember);
      //跳转
      //console.log('[MemberLogin-CTL]arg.direct:' + this.member.redirect + ', arg.refere:' + this.previousUrl);
      this.processRedirectURL(this.member.redirect || this.previousUrl);
    }
  }

  private processRedirectURL(argDedirectURL: string | null): void {
    //console.log('[MemberLogin-CTL]process URL:' + argDedirectURL);
    //是否有参数
    let redirectURL: string = argDedirectURL || '/home';
    let data: ProcessURLResult = this.footMark.processURL(redirectURL);
    this.router.navigate([data.path], { queryParams: data.queryParams });
  }
}
